package org.ch02.test00.demo09.myWork;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.ch02.test00.demo06.myWork.SqlGenerate;

import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author CSY
 * @date 2025 - 03 - 19
 */
public class DbUtil {
    private static DataSource dataSource;

    public static DataSource getDataSource() {
        if (dataSource == null) {
            initDataSource();
        }
        return dataSource;
    }

    public static void initDataSource() {
        Properties prop = new Properties();
        try {
            prop.load(org.ch02.test00.demo08.myWork.DbUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static int executeUpdate(String sql, Object... params) {
        int n = 0;
        Connection conn = getConnection();
        PreparedStatement psmt = null;
        try {
            psmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                psmt.setObject(i + 1, params[i]);
            }
            n = psmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return n;
    }

    public static void close(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void insert(Object entity){
        Class<?> clazz = entity.getClass();
        String sql = getInsertSql(clazz);
        System.out.println(sql);
        Field[] fields = clazz.getDeclaredFields();
        Object[] val = new Object[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fields[i].setAccessible(true);

            try {
                val[i] = fields[i].get(entity);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        int n = DbUtil.executeUpdate(sql, val);
        if (n > 0) {
            System.out.println("添加成功！");
        }
    }

    public static String getInsertSql(Class<?> clazz){
        //        String sql = "insert into staffs(name,age,phone,sta_pos) values ('王五',20,'13417747373','教授');";
        StringBuilder sql = new StringBuilder("insert into ");
        //加入添加的表名
        sql.append(SqlGenerate.convert(clazz.getSimpleName())).append("(");
        //获取所有字段对象
        Field[] declaredFields = clazz.getDeclaredFields();
        String param = "";
        for (Field f : declaredFields) {
            //设置权限
            f.setAccessible(true);

            //要添加的字段名
            sql.append(SqlGenerate.convert(f.getName())).append(",");
            param += "?,";
        }
        //删除最后的逗号
        sql.deleteCharAt(sql.length() - 1);
        param = param.substring(0, param.length() - 1);
        sql.append(") values(").append(param).append(")");
        return sql.toString();
    }
}
